/*
 * 时间帧输入控件
 * author luanzg | date 20200825
 */
<template>
  <div v-if="inputType === 'text'" :class="[
    inputType === 'textarea' ? 'el-textarea' : 'el-input',
    inputSize ? 'el-input--' + inputSize : '',
    'el-input--prefix',
    {
      'is-disabled': inputDisabled
    }
    ]"
  >
    <i :class="['el-input__icon', 'el-range__icon']"></i>
    <input
      class="el-input__inner"
      ref="input"
      :type="inputType"
      v-on:compositionend="endInputhandle"
      v-on:compositionstart="cpLock = true"
      @input="handleInput"
      @keydown.prevent="handleKeydown"
      :placeholder="placeholder"
      @blur="handleBlur"
      :disabled="inputDisabled"
      :readonly="readonly"/>
    <span class="el-input__prefix">
      <i class="el-input__icon el-icon-time"></i>
    </span>
  </div>
  <div v-else>
    <span>{{this.nativeInputValue}}</span>
  </div>
</template>

<script>
export default {
  name: 'TimePicker',
  data() {
    return {
      oldVlue: '',
      cpLock: false,
      srfstr: '',
      initVlue: ''
    }
  },
  props: {
    value: {
      type: [String, Number],
      default: 0
    },
    inputType: {
      type: String,
      default: 'text'
    },
    placeholder: {
      type: String,
      default: '我是时间插件'
    },
    format: {
      type: String,
      default: 'HH:ii:ss-ms'
    },
    size: String,
    disabled: Boolean,
    readonly: Boolean,
    fps4k: Boolean
  },
  computed: {
    nativeInputValue() {
      return this.value === null || this.value === undefined
        ? '00:00:00' + (this.format === 'HH:ii:ss-ms' ? '-00' : '')
        : this.formatMethod(this.value)
    },
    inputSize() {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size
    },
    inputDisabled() {
      return this.disabled
    },
    inputfps4k() {
      return this.fps4k
    }
  },
  watch: {
    nativeInputValue(newV, oldV) {
      this.setNativeInputValue()
    }
  },
  methods: {
    // 时间帧数进行时间格式转换
    formatMethod(value) {
      const fpsNum = parseInt(value)
      const fMaxsm = this.fps4k ? 20 : 40
      const ssArr = (fpsNum * fMaxsm / 1000).toFixed(2).split('.')
      let thetime = '00' // 秒
      let middle = '00' // 分
      let hour = '00' // 时
      let fps = '00' // 帧
      let result = ''
      thetime = parseInt(ssArr[0])
      if (thetime > 59) {
        middle = parseInt(thetime / 60)
        thetime = parseInt(thetime % 60)

        if (middle > 59) {
          hour = parseInt(middle / 60)
          middle = parseInt(middle % 60)
        }
      }
      // 帧数转换
      if (parseInt(ssArr[1]) > 0) {
        fps = parseInt(ssArr[1]) * 10 / fMaxsm
      }
      result += String(hour).padStart(2, '0') + ':'
      result += String(middle).padStart(2, '0') + ':'
      result += String(thetime).padStart(2, '0')
      if (this.format === 'HH:ii:ss-ms') {
        result += '-' + String(fps).padStart(2, '0')
      }
      return result
    },
    strototime(timestr) {
      let ssmils = 0
      let fps = 0
      const ssmilsfps = this.fps4k ? 50 : 25 // 配置1s 等于的帧数
      const tarr = timestr.substring(0, 8).split(':')
      if (this.format === 'HH:ii:ss-ms') {
        fps = parseInt(timestr.substring(9, 11))
      } else {
        fps = 0
      }

      if (parseInt(tarr[0]) > 0) {
        ssmils += parseInt(tarr[0]) * 60 * 60
      }

      if (parseInt(tarr[1]) > 0) {
        ssmils += parseInt(tarr[1]) * 60
      }

      if (parseInt(tarr[2]) > 0) {
        ssmils += parseInt(tarr[2])
      }
      return ssmils * ssmilsfps + fps
    },
    setNativeInputValue() {
      const input = this.getInput()
      if (!input) return
      if (input.value === this.nativeInputValue) return
      input.value = this.nativeInputValue
    },
    getInput() {
      return this.$refs.input
    },
    handleInput(event) {
      this.oldVlue = JSON.parse(JSON.stringify(event.target.value))
      if (this.cpLock) {
        this.srfstr = event.data
        return false
      }
      if (!/\d/.test(event.data)) {
        this.srfstr = event.data
        this.oldVlue = JSON.parse(JSON.stringify(event.target.value))
        event.target.value = this.oldVlue.replace(this.srfstr, '')
      }
      event.stopPropagation()
      return false
    },
    handleKeydown(event) {
      if (!this.isNumber(event.keyCode)) return false
      if (this.readonly) return false
      let step, bckstr, result, intd, iSertnum, resultNum
      const elInput = event.target
      const startPos = elInput.selectionStart
      const endPos = elInput.selectionEnd
      if (startPos === undefined || endPos === undefined) return

      this.oldVlue = JSON.parse(JSON.stringify(event.target.value))
      if (event.keyCode === 8) {
        bckstr = this.oldVlue.slice(endPos - 1, endPos)
        if (bckstr === null || bckstr === '') return
        setTimeout(() => {
          if (bckstr === '-' || bckstr === ':') {
            result = this.oldVlue.substring(0, startPos - 2) + '0' + bckstr + this.oldVlue.substring(endPos)
          } else {
            result = this.oldVlue.substring(0, startPos - 1) + '0' + this.oldVlue.substring(endPos)
          }

          elInput.value = result
          elInput.focus()
          if (bckstr === '-' || bckstr === ':') {
            step = 2
          } else {
            step = 1
          }
          elInput.selectionStart = endPos - step
          elInput.selectionEnd = endPos - step
          this.$emit('input', this.strototime(elInput.value))
        }, 0)
      } else if (event.keyCode === 37 || event.keyCode === 38) {
        elInput.selectionStart = (endPos - 1) > 0 ? endPos - 1 : 0
        elInput.selectionEnd = (endPos - 1) > 0 ? endPos - 1 : 0
      } else if (event.keyCode === 39 || event.keyCode === 40) {
        elInput.selectionStart = endPos + 1
        elInput.selectionEnd = endPos + 1
      } else {
        intd = this.getNumber(event.keyCode) // 获取输入的数字
        if ([0, 1].indexOf(startPos) > -1) {
          if (startPos === 0) {
            iSertnum = intd + this.oldVlue.substring(1, 2)
          } else {
            iSertnum = this.oldVlue.substring(0, 1) + intd
          }
          if (iSertnum > 99) return false
        } else if ([3, 4].indexOf(startPos) > -1) {
          if (startPos === 3) {
            iSertnum = intd + this.oldVlue.substring(4, 5)
          } else {
            iSertnum = this.oldVlue.substring(3, 4) + intd
          }
          if (iSertnum > 59) return false
        } else if ([6, 7].indexOf(startPos) > -1) {
          if (startPos === 6) {
            iSertnum = intd + this.oldVlue.substring(7, 8)
          } else {
            iSertnum = this.oldVlue.substring(6, 7) + intd
          }
          if (iSertnum > 59) return false
        } else if ([9, 10].indexOf(startPos) > -1 && this.format === 'HH:ii:ss-ms') {
          if (startPos === 9) {
            iSertnum = intd + this.oldVlue.substring(10, 11)
          } else {
            iSertnum = this.oldVlue.substring(9, 10) + intd
          }

          if (this.inputfps4k) {
            if (iSertnum > 50) return false
          } else {
            if (iSertnum > 25) return false
          }
        } else {
          elInput.selectionStart = startPos + 1
          elInput.selectionEnd = startPos + 1
          return false
        }
        resultNum = this.oldVlue.substring(0, startPos) + intd + this.oldVlue.substring(startPos + 1)
        if (resultNum !== undefined || resultNum !== '') {
          setTimeout(() => {
            elInput.value = resultNum
            elInput.selectionStart = startPos + 1
            elInput.selectionEnd = startPos + 1
            this.$emit('input', this.strototime(elInput.value))
          }, 0)
        }
      }
    },

    // 仅能输入数字
    isNumber(keyCode) {
      // 数字
      if (keyCode >= 48 && keyCode <= 57) return true

      // 小数字键盘

      if (keyCode >= 96 && keyCode <= 105) return true

      // Backspace, del, 上下左右方向键

      if (keyCode === 8 || keyCode === 46 || keyCode === 37 || keyCode === 39 || keyCode === 38 || keyCode === 40) return true

      return false
    },

    // 获取输入的数字
    getNumber(keyCode) {
      const numobj = {
        48: 0,
        49: 1,
        50: 2,
        51: 3,
        52: 4,
        53: 5,
        54: 6,
        55: 7,
        56: 8,
        57: 9,
        96: 0,
        97: 1,
        98: 2,
        99: 3,
        100: 4,
        101: 5,
        102: 6,
        103: 7,
        104: 8,
        105: 9
      }
      return numobj[keyCode]
    },
    // 输入法结束回调
    endInputhandle(event) {
      this.oldVlue = JSON.parse(JSON.stringify(event.target.value))
      event.target.value = this.oldVlue.replace(this.srfstr, '')
      this.cpLock = false
    },
    handleBlur() {
      this.$emit('blur')
      if (this.initVlue !== this.nativeInputValue) {
        this.$emit('change')
        this.initVlue = this.nativeInputValue
      }
    }
  },
  updated() {
    this.setNativeInputValue()
  },
  mounted() {
    this.initVlue = this.nativeInputValue
    this.setNativeInputValue()
  }
}
</script>

<style>
</style>
